<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "yyh_user".
 *
 * @property int $id
 * @property string $username 登录ID
 * @property string $password
 * @property string $showname 姓名
 * @property string|null $ordernumber 预约号
 * @property string|null $tellphone 电话号码
 * @property string|null $workgroup 群组
 * @property int|null $job 职位
 * @property string $status 状态
 * @property string $createtime 创建时间
 */
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    private static $users = [];

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'yyh_user';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['username', 'password', 'showname', 'status', 'createtime'], 'required'],
            [['workgroup', 'status'], 'string'],
            [['job', 'department_id'], 'integer'],
            [['createtime'], 'safe'],
            [['username', 'password', 'showname', 'ordernumber'], 'string', 'max' => 32],
            [['tellphone'], 'string', 'max' => 11],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '登录名',
            'password' => '密码',
            'showname' => '姓名',
            'ordernumber' => '预约号',
            'tellphone' => '电话号码',
            'workgroup' => '群组',
            'job' => '职位',
            'status' => '状态',
            'department_id' => '所属科室',
            'createtime' => '创建时间',
        ];
    }

    private static function get_users()
    {
        if (count(self::$users) < 1) {
            $objs = User::find()->all();
            foreach ($objs as $u) {
                $users[$u->id] = $u;
            }
            self::$users = $users;
        }

        return self::$users;
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        self::get_users();
        return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        self::get_users();
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        self::get_users();
        foreach (self::$users as $user) {
            if (strcasecmp($user->username, $username) === 0) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === substr(md5($password), 5, 20);
    }

    public function getJobname()
    {
        $id = (int)$this->job;
        $job = Job::find()->where("id = {$id}")->one();
        if ($job != null) {
            return $job->name;
        } else {
            return null;
        }
    }

    public function getMenus()
    {
        $job = Job::find()->where("id = {$this->job}")->one();
        if ($job->name == '超级管理员') {
            return 'all';
        } else {
            if (!empty(trim($job->menu_powers))) {
                $menus = Menu::find()->where("id in ({$job->menu_powers})")->all();
                $res = array();
                foreach ($menus as $m) {
                    $res[$m->url] = $m->name;
                }
                return $res;
            }
        }
        return null;
    }

    //获得用户列表，checked_ids_string用于select的option，limit限定是否只显示checked_ids_string中的用户
    public static function getTreeData($where = '', $checked_ids_string = '', $limit = false)
    {
        $user_array = User::find()->select('id, showname as name')->where($where)->asArray()->all();
        $limit_user_array = [];
        if ($checked_ids_string != '') {
            $id_array = explode(",", $checked_ids_string);
            if (null != $id_array && count($id_array) > 0) {
                foreach ($id_array as $value_id) {
                    foreach ($user_array as $i => $d) {
                        if ((int)$d['id'] == (int)trim($value_id)) {
                            $user_array[$i]['checked'] = true;
                            if ($limit == true) {
                                $limit_user_array[] = $user_array[$i];
                            }
                        }
                    }
                }
            }
        }
        if ($limit == true) {
            return $limit_user_array;
        } else {
            return $user_array;
        }
    }

    public function getJobModel()
    {
        return Job::findOne($this->job);
    }
}
